/**
 * @description typeModel Service
 */

const {
  typeModel
} = require('../db/index')
const Op = require('sequelize').Op

async function addData(params) {
  if (!params.parentId) {
    delete params.parentId
  }
  // 判断名称是否重复
  let item = await typeModel.findAll({
    where: {
      name: params.name
    }
  })
  if (item.length) {
    return 'error'
  }
  const result = await typeModel.create(params)
  const data = result.dataValues
  return data
}

async function updateData(
  params,
  id
) {
  // 拼接修改内容
  const updateObj = params

  // 拼接查询条件
  const whereOption = {}
  if (id) {
    whereOption.id = id
  }

  // 执行修改
  const result = await typeModel.update(updateObj, {
    where: whereOption
  })
  return result[0] > 0
}

async function deleteData(id) {
  console.log(id)
  const result = await typeModel.destroy({
    where: {
      id
    }
  })
  return result > 0
}

async function queryByNo(no) {
  const result = await typeModel.findAll({
    where: {
      no
    }
  })
  return {
    exsit: !!result.length
  }
}

async function queryAll(params) {
  console.log(params)
  const {
    page = 1,
    pageSize = 10,
    name,
    type,
    category,
    order
  } = params
  if (page < 1) {
    page = 1
  }
  console.log(name)
  let whereOption = {}
  if (name) {
    whereOption.name = {
      [Op.like]: `%${name}%`
    }
  }

  if (type) {
    whereOption.type = type
  }
  if (category) {
    whereOption.category = category
  }
  if (order) {
    if (order == '推荐') {
      const result = await typeModel.findAll({
        limit: pageSize,
        offset: (page - 1) * pageSize,
        where: whereOption,
        order: [
          ['sell', 'desc']
        ],
      })
      console.log(result)
      const total = await typeModel.findAll({
        where: whereOption
      })
      return {
        page,
        pageSize,
        total: total.length || 0,
        data: result || []
      }
    }
  }
  const result = await typeModel.findAll({
    limit: pageSize,
    offset: (page - 1) * pageSize,
    where: whereOption
  })
  console.log(result)
  const total = await typeModel.findAll({
    where: whereOption
  })
  return {
    page,
    pageSize,
    total: total.length || 0,
    data: result || []
  }
}

module.exports = {
  addData,
  updateData,
  deleteData,
  queryAll,
  queryByNo
}